<template>
  <div>
    <br/><br/><br/><br/>
    <span style=""><strong style="font-size: 20px">购物车</strong>(全部{{ this.total }}件)</span>
    <br/><br/>
    <div >
      <el-table ref="multipleTable" :data="cartList" tooltip-effect="dark" style="width: 1300px;"
                @selection-change="changeCartIds" show-overflow-tooltip border stripe>
        <el-table-column align="center" label="鲜花id" prop="flowerId" type="selection">
        </el-table-column>
        <el-table-column align="center" label="鲜花名称" prop="flowerId">
          <template slot-scope="scope">
            {{ scope.row.flowerName }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="图片" prop="flowerImg" width="300px">
          <template slot-scope="scope">
            <img :src="'http://localhost:8088/image'+scope.row.flowerImg" style="width: 200px; height: 200px;"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="单价" prop="flowerPrice" width="100px">
        </el-table-column>
        <el-table-column align="center" label="购买数量" prop="buyCount" width="200px">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.buyCount"
                             @change="updateBuyCountByCartId(scope.row.buyCount,scope.row.cartId)"
                             size="mini" :min="1">
            </el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="金额（元）" width="100px">
          <template slot-scope="scope">
            ￥{{ scope.row.buyCount * scope.row.flowerPrice }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="类别" prop="typeId">
          <template slot-scope="scope">
            {{ scope.row.typeName }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="danger" @click="deleteCartByCartId(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <br/>
      <br/>
      <el-button type="danger" plain @click="deleteMoreCart()"
                 style="margin-left: 50px;float: left;margin-top: -10px">删除所选
      </el-button>
      <!--分页插件-->
      <div class="block" style="margin-left: 450px;margin-bottom: 20px">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page=pageNum
            :page-sizes="[5,10]"
            :page-size=pageSize
            layout="total, sizes, prev, pager, next, jumper"
            :total=total>
        </el-pagination>
      </div>
    </div>
    <el-divider></el-divider>
    <div style="margin-left: 850px;">
      <span>已选择件{{ this.cartIds.length }}商品</span>
      <span style="margin-left: 20px">共计{{ this.totalPrice }}元</span>
      <el-button style="margin-left: 50px;width: 150px;color: red" type="primary" plain @click="insertFlowerOrder()">下单
      </el-button>
    </div>
  </div>
</template>

<script>
import {Message} from "element-ui";

export default {
  name: "CartView",
  data() {
    return {
      accountId: '2',
      accountName: 'jack',
      pageNum: 1,
      pageSize: 5,
      total: 0,

      cartList: [],
      cartIds: [],
      totalPrice: 0,
    }
  },
  created() {
    this.getLogin();
    this.selectAllCartByAccountId();
  },
  methods: {
    getLogin() {
      this.accountId = sessionStorage.getItem("accountId");
      this.accountName = sessionStorage.getItem("accountName");
    },

    // 查询购物车列表
    selectAllCartByAccountId() {
      let url = "/flowerCart/selectAllCartByAccountId";
      this.$axios.get(url, {
        params: {
          accountId: this.accountId,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
      }).then(res => {
        this.cartList = res.data.data.list;
        this.total = res.data.data.total;
      })
    },

    // 改变购物车id列表
    changeCartIds(val) {
      let temp = [];
      let tempPrice = 0;
      for (let i = 0; i < val.length; i++) {
        temp.push(val[i].cartId);
        tempPrice += val[i].buyCount * val[i].flowerPrice;
      }
      this.cartIds = temp;
      this.totalPrice = tempPrice;
    },

    // 改变购买数量
    updateBuyCountByCartId(buyCount, cartId) {
      let url = "/flowerCart/updateBuyCountByCartId";
      let params = new URLSearchParams;
      params.append("buyCount", buyCount);
      params.append("cartId", cartId);
      this.$axios.post(url, params)
          .then(res => {
            if (res.data.code == 200) {
              let temp = 0;
              for (let i = 0; i < this.cartList.length; i++) {
                for (let j = 0; j < this.cartIds.length; j++) {
                  if (this.cartList[i].cartId == this.cartIds[j]) {
                    temp += this.cartList[i].buyCount * this.cartList[i].flowerPrice;
                  }
                }
              }
              this.totalPrice = temp;
            } else {
              Message({
                type: "error",
                message: res.data.msg,
                duration: 1000,
              });
            }
          })
    },

    // 删除购物车数据
    deleteCartByCartId(row) {
      let url = "/flowerCart/deleteCartByCartId";
      let params = new URLSearchParams;
      params.append("cartId", row.cartId);
      this.$axios.post(url, params)
          .then(res => {
            if (res.data.code == 200) {
              Message({
                type: "success",
                message: res.data.msg,
                duration: 1000,
              });
              this.selectAllCartByAccountId();
            } else {
              Message({
                type: "error",
                message: res.data.msg,
                duration: 1000,
              });
            }
          })
    },

    // 分页相关
    handleSizeChange(val) {
      this.pageSize = val;
      this.selectAllCartByAccountId();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.selectAllCartByAccountId();
    },

    // 下单
    insertFlowerOrder() {
      if (this.cartIds.length == 0) {
        Message({
          type: "error",
          message: "请至少选择一项",
          duration: 1000,
        });
        return;
      } else {
        let params = new URLSearchParams;
        params.append("cartIds", this.cartIds);
        this.$axios.post("/flowerInfo/checkFlowerInfoCount", params).then(res => {
          if (res.data.code == 500) {
            Message({
              type: "error",
              message: res.data.msg,
              duration: 1000,
            })
            return;
          } else {
            let url = "/flowerOrder/insertFlowerOrderFromCart";
            let params = new URLSearchParams();
            params.append("accountId", this.accountId);
            params.append("cartIds", this.cartIds)
            this.$axios.post(url, params)
                .then(res => {
                  if (res.data.code == 200) {
                    Message({
                      type: "success",
                      message: res.data.msg,
                      duration: 1000,
                    });
                    sessionStorage.setItem("orderId", res.data.data);
                    this.$router.push('/checkOut');
                  } else if(res.data.code==300){
                    Message({
                      message: res.data.msg,
                      type: "error",
                      duration: 1000
                    })
                    this.$router.push('/site');
                  }else {
                    Message({
                      type: "error",
                      message: res.data.msg,
                      duration: 1000,
                    });
                  }
                });
          }
        })
      }
    },

    // 一次性多删除购物车数据
    deleteMoreCart() {
      if (this.cartIds.length == 0) {
        Message({
          type: "error",
          message: "请至少选择一项",
          duration: 1000,
        })
      } else {
        let url = "/flowerCart/deleteMoreCart";
        let params = new URLSearchParams();
        params.append("cartIds", this.cartIds);
        this.$axios.post(url, params)
            .then(res => {
              if (res.data.code == 200) {
                Message({
                  type: "success",
                  message: res.data.msg,
                  duration: 1000,
                });
                this.selectAllCartByAccountId();
                this.cartIds = [];
              } else {
                Message({
                  type: "error",
                  message: res.data.msg,
                  duration: 1000,
                });
              }
            })
      }
    },
  }
}
</script>

<style>
body {
  //background-color: lightpink;
}
</style>